package org.txazo.blog.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.txazo.blog.service.MemberInfoService;
import org.txazo.blog.service.MemberLoginInfoService;
import org.txazo.blog.util.CookieUtil;
import org.txazo.blog.util.StringUtil;
import org.txazo.blog.vo.MemberInfo;

/**
 * 自动登录过滤器
 * 
 * @author Tu XiaoZhou
 * @since 2013-08-10
 */
public class AutoLoginSessionFilter implements Filter {

	@Override
	public void init(FilterConfig arg0) throws ServletException {
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		HttpSession session = request.getSession();

		MemberInfo memberInfo = (MemberInfo) session.getAttribute("memberInfo");

		if (memberInfo == null) {
			/** ^~^autoLogin=value^~^emailAccount=value^~^password =value^~^ */
			String autoLogin = CookieUtil.getCookie(request, response, "login",
					"autoLogin");
			if (StringUtil.isNotEmpty(autoLogin)) {
				String emailAccount = CookieUtil.getCookie(request, response,
						"login", "emailAccount");
				String password = CookieUtil.getCookie(request, response,
						"login", "password");
				if (StringUtil.isNotEmpty(emailAccount)
						&& StringUtil.isNotEmpty(password)) {
					ApplicationContext context = WebApplicationContextUtils
							.getWebApplicationContext(request
									.getServletContext());
					MemberLoginInfoService memberLoginInfoService = (MemberLoginInfoService) context
							.getBean("memberLoginInfoService");
					if (memberLoginInfoService.loginValidate(emailAccount,
							password)) {
						MemberInfoService memberInfoService = (MemberInfoService) context
								.getBean("memberInfoService");
						memberInfo = memberInfoService
								.getMemberInfo(emailAccount);

						session.setAttribute("memberInfo", memberInfo);
					}
				}
			}
		}

		chain.doFilter(req, resp);
	}

	@Override
	public void destroy() {
	}

}
